<template>
  <div>
    <el-main>
      <div class="box">
        <div class="top">
          <el-form
            :inline="true"
            :model="queryForm"
            class="demo-form-inline"
            style="float: left"
            label-suffix=":"
            size="medium"
          >
            <el-form-item label="统计方式">
              <el-select
                v-model="queryForm.radio"
                placeholder="请选择"
                style="width: 160px"
                @change="onRadioChange"
              >
                <el-option label="月度统计" value="month"></el-option>
                <el-option label="年度统计" value="year"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="时间">
              <el-date-picker
                v-model="queryForm.yearMonth"
                style="width: 160px"
                :default-value="currentDate"
                @change="onDateChange"
                :type="queryForm.radio === 'month' ? 'month' : 'year'"
                :clearable="false"
                placeholder="选择时间"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="tongji">统计</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="center" v-if="areacode == '1506'">
          <el-table
            :data="paginatedData"
            border
            style="width: 100%"
            size="medium"
            show-summary
            :summary-method="tableSummaryMethod"
          >
            <el-table-column
              prop="xzqhname"
              label="旗区"
              show-overflow-tooltip
            />
            <el-table-column
              prop="totalkf"
              label="扣分"
              :formatter="formatNumber"
              show-overflow-tooltip
            />
            <el-table-column
              prop="kouqian"
              label="缴纳补偿金(万元)"
              :formatter="formatNumber"
              show-overflow-tooltip
            />
            <el-table-column
              prop="totaldf"
              label="得分"
              :formatter="formatNumber"
              show-overflow-tooltip
            />
            <el-table-column
              prop="scoreRatio"
              label="得分占比"
              :formatter="formatPercentage"
              show-overflow-tooltip
            />
            <el-table-column
              prop="fenpeikf"
              label="分配补偿金(万元)"
              :formatter="formatNumber"
              show-overflow-tooltip
            />
            <el-table-column
              prop="deqian"
              label="得到补偿金(万元)"
              :formatter="formatNumber"
              show-overflow-tooltip
            />
          </el-table>
        </div>
        <div class="center" v-else>
          <el-table
            :data="paginatedData"
            border
            style="width: 100%"
            size="medium"
          >
            <el-table-column
              prop="xzqhname"
              label="旗区"
              show-overflow-tooltip
            />
            <el-table-column
              prop="totalkf"
              label="扣分"
              :formatter="formatNumber"
              show-overflow-tooltip
            />
            <el-table-column
              prop="kouqian"
              label="缴纳补偿金(万元)"
              :formatter="formatNumber"
              show-overflow-tooltip
            />
            <el-table-column
              prop="totaldf"
              label="得分"
              :formatter="formatNumber"
              show-overflow-tooltip
            />
            <el-table-column
              prop="scoreRatio"
              label="得分占比"
              :formatter="formatPercentage"
              show-overflow-tooltip
            />
            <el-table-column
              prop="fenpeikf"
              label="分配补偿金(万元)"
              :formatter="formatNumber"
              show-overflow-tooltip
            />
            <el-table-column
              prop="deqian"
              label="得到补偿金(万元)"
              :formatter="formatNumber"
              show-overflow-tooltip
            />
          </el-table>
        </div>
      </div>

      <div class="bottom">
        <el-pagination
          :current-page="currentPage"
          hide-on-single-page
          background
          layout="total, prev, pager, next, jumper"
          :total="totalItems"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-main>
  </div>
</template>

<script>
import { GetPermission } from "@/utils/auth.js";
export default {
  name: "CompensationStatistics",
  data() {
    return {
      areacode: "1506",
      queryForm: {
        yearMonth: "",
        radio: "month", // 默认月度统计
        selectedXzqh: "1506", // 默认选中全部
      },
      paginatedData: [], // 当前页的数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的数据量
      totalItems: 0, // 总项目数
    };
  },
  created() {
    let areacode = GetPermission().areacode;
    this.areacode = areacode;
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1;
    this.queryForm.yearMonth = `${year}-${month < 10 ? "0" + month : month}`;
  },
  computed: {
    currentDate() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;
      return `${year}-${month < 10 ? "0" + month : month}`;
    },
  },
  methods: {
    // 格式化为两位小数，不四舍五入
    formatNumber(row, column, cellValue) {
      return cellValue !== undefined && cellValue !== null
        ? (Math.floor(parseFloat(cellValue) * 100) / 100).toFixed(2)
        : "0.00";
    },

    // 格式化为百分比
    // formatPercentage(row, column, cellValue) {
    //   return cellValue !== undefined && cellValue !== null
    //     ? `${parseFloat(cellValue).toFixed(2)}%`
    //     : "0.00%";
    // },
    // 格式化为百分比
    formatPercentage(row, column, cellValue) {
      if (cellValue !== undefined && cellValue !== null) {
        // 将数字转化为两位小数，不进行四舍五入
        const percentage = Math.floor(parseFloat(cellValue) * 100) / 100;

        // 检查是否是整数，若是整数就去掉小数部分
        return percentage % 1 === 0
          ? `${parseInt(percentage)}%`
          : `${percentage.toFixed(2)}%`; // 保证保留两位小数
      }
      return "0%"; // 如果没有值，显示 0%
    },

    // 计算分配补偿金
    calculateFenpeiKf(x) {
      const increments = [];
      let compensation = 0;

      // 生成增量 (25, 50, 75, 100,...)
      for (let i = 0; i < 10; i++) {
        increments.push(25 * (i + 1)); // 生成增量：25, 50, 75, 100,...
      }

      // 遍历区间，根据扣分值x计算补偿金额
      for (let i = 0; i < increments.length; i++) {
        if (x > i && x <= i + 1) {
          compensation += increments[i] * (x - i); // 当前区间的补偿金额
          break; // 一旦找到符合条件的区间就跳出循环
        } else if (x > i + 1) {
          compensation += increments[i]; // 累加已通过区间的固定补偿金额
        }
      }

      return compensation;
    },
    tableSummaryMethod(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          // 保证总计结果保留两位小数，不进行四舍五入
          sums[index] = (Math.floor(sums[index] * 100) / 100).toFixed(2);
          if (index === 4) {
            sums[4] += "%";
          }
          if (index === 6) {
            // 假设“得到补偿金(万元)”是第7列（索引为6）
            console.log("总计得到补偿金(万元):", sums[index]); // 打印总计补偿金
            // sums[index] = parseFloat(sums[index]).toFixed(2);
            sums[index] = (
              Math.floor(parseFloat(sums[index]) * 100) / 100
            ).toFixed(2);
            console.log("总计得到补偿金(万元):", sums[index]); // 打印总计补偿金
          }
        }
      });

      return sums;
    },

    onRadioChange() {
      this.queryForm.yearMonth =
        this.queryForm.radio === "month"
          ? this.currentDate
          : `${new Date().getFullYear()}`;
      this.fetchData();
    },

    onDateChange(date) {
      if (!date) return;
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      this.queryForm.yearMonth = `${year}-${month < 10 ? "0" + month : month}`;
      // this.fetchData();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },

    tongji() {
      this.fetchData();
    },

    fetchData() {
      const { yearMonth, selectedXzqh, radio } = this.queryForm;
      let tjsj = "";

      if (radio === "month") {
        tjsj = yearMonth;
      } else if (radio === "year") {
        tjsj = yearMonth.split("-")[0];
      }

      const xzqhdm = selectedXzqh;

      this.$api
        .monthTotalData(xzqhdm, tjsj)
        .then((response) => {
          const data = response.data.data;
          // 扣分
          // const totalKf = data.reduce((acc, item) => acc + item.totalkf, 0);
          // console.log('扣分',totalKf);

          const totalDf = data.reduce((acc, item) => acc + item.totaldf, 0);
          const totalKouqian = data.reduce((acc, item) => acc + this.calculateFenpeiKf(item.totalkf), 0);
          // const totalKouqian = data.reduce(
          //   (acc, item) => acc + this.calculateFenpeiKf(45000),
          //   0
          // );
          console.log("总计缴纳补偿", totalKouqian);

          this.paginatedData = data.map((item) => {
            const scoreRatio = totalDf
              ? (item.totaldf / totalDf) * 100 // 使用精确值计算
              : 0;
            console.log("777", scoreRatio);

            const kouqian = this.calculateFenpeiKf(item.totalKf);
            // const kouqian = this.calculateFenpeiKf(45000);
            // 计算分配补偿金
            const fenpeikf = totalKouqian * (scoreRatio / 100);

            // 得到补偿金
            const deqian = fenpeikf - kouqian;
            console.log("得到补偿金", deqian);

            return {
              ...item,
              kouqian: kouqian,
              scoreRatio: scoreRatio,
              fenpeikf: fenpeikf,
              deqian: deqian,
            };
          });
          if (this.areacode !== "1506") {
            this.paginatedData = this.paginatedData.filter(
              (item) => item.xzqhcode == this.areacode
            );
          }
          // this.totalItems = response.data.totalItems;
          // 筛选出扣分为1的记录
        })
        .catch((error) => {
          console.error("数据请求失败", error);
        });
    },
  },
};
</script>

<style scoped></style>
